package com.pay.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.entity.Merchant;
import com.pay.entity.MerchantAccountDetail;
import com.pay.enums.MerchantAccountTypeEnums;
import com.pay.exception.ServiceException;
import com.pay.mapper.MerchantAccountDetailMapper;
import com.pay.service.IMerchantAccountDetailService;
import com.pay.service.IMerchantAccountService;
import com.pay.service.IMerchantService;
import com.pay.utils.BasePage;
import com.pay.utils.ResponseData;

import cn.hutool.core.util.StrUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Peng
 * @since 2018-12-10
 */
@Service
public class MerchantAccountDetailServiceImpl extends ServiceImpl<MerchantAccountDetailMapper, MerchantAccountDetail> implements IMerchantAccountDetailService {

	@Autowired
	private IMerchantService merchantService ;
	
	@Autowired
	private IMerchantAccountService merchantAccountService ;
	
	@Override
	public void getList(MerchantAccountDetail merchantAccountDetail, BasePage<MerchantAccountDetail> basePage) {
		basePage.setSize(20) ;
		QueryWrapper<MerchantAccountDetail> ew = new QueryWrapper<MerchantAccountDetail>();
		ew.orderByDesc("id") ;
		if(merchantAccountDetail.getMerId() != null) {
			ew.eq("mer_id", merchantAccountDetail.getMerId()) ;
		}
		if(basePage.isPage()) {
			super.page(basePage, ew) ;
		}else {
			List<MerchantAccountDetail> data = super.list(ew);
			int total = super.count(ew);
			basePage.setRecords(data) ;
			basePage.setTotal(total) ;
		}
		
		for(MerchantAccountDetail detail : basePage.getRecords()) {
			Merchant merchant = merchantService.getById(detail.getMerId());
			String typename = MerchantAccountTypeEnums.getName(detail.getTypeid());
			detail.setMerchant(merchant);
			detail.setTypename(typename);
		}
	}

	@Override
	public ResponseData doMerchantAccountPreper(MerchantAccountDetail merchantAccountDetail) {
		if(merchantAccountDetail.getMerId() == null) {
			return ResponseData.baseError("商户id不能为空") ;
		}
		if(merchantAccountDetail.getIsout() == null) {
			return ResponseData.baseError("收支状态不能为空") ;
		}
		if(merchantAccountDetail.getCost().compareTo(BigDecimal.ZERO) <= 0) {
			return ResponseData.baseError("操作金额必须大于0") ;
		}
		String remark = MerchantAccountTypeEnums.getName(merchantAccountDetail.getTypeid()) ;
		String result = merchantAccountService.insertAccountDetail(merchantAccountDetail.getMerId(), merchantAccountDetail.getTypeid(),
				merchantAccountDetail.getIsout(), merchantAccountDetail.getCost(), remark);
		if(StrUtil.isBlank(result)) {
			return ResponseData.ok() ;
		}else {
			throw new ServiceException("操作失败") ;
		}
	}

}
